//
// Created by zql on 2022/3/17.
//

#include "epoller.h"

Epoller::Epoller(int max_events) {
    m_epoll_fd = epoll_create(512);
    assert(m_epoll_fd >= 0 && max_events >= 0);
    m_events = std::vector<struct epoll_event>(max_events);
    m_max_events = max_events;
}

Epoller::~Epoller() {
    close(m_epoll_fd);
}

int Epoller::add_fd(int fd, const uint32_t events) const {
    if (fd < 0)
        return false;
    epoll_event ev{};
    ev.data.fd = fd;
    ev.events = events;
    return epoll_ctl(m_epoll_fd, EPOLL_CTL_ADD, fd, &ev);
}

int Epoller::mod_fd(int fd, uint32_t events) const {
    if (fd < 0)
        return false;
    epoll_event ev{};
    ev.data.fd = fd;
    ev.events = events;
    return epoll_ctl(m_epoll_fd, EPOLL_CTL_MOD, fd, &ev);
}

int Epoller::del_fd(int fd) const {
    if (fd < 0)
        return false;
    return epoll_ctl(m_epoll_fd, EPOLL_CTL_DEL, fd, nullptr) == 0;
}

int Epoller::wait(int timeout_ms) {
    return epoll_wait(m_epoll_fd, &m_events[0], m_max_events, timeout_ms);
}

int Epoller::get_event_fd(size_t i) {
    assert(i >= 0 && i < m_max_events);
    return m_events[i].data.fd;
}

uint32_t Epoller::get_events(size_t i) {
    assert(i >= 0 && i < m_max_events);
    return m_events[i].events;
}




